package service

import (
	"ams/global"
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
	"lib/structs/ams"
	"lib/structs/base"
	"net/http"
	"strings"
)

var DsService = new(deepService)

type deepService struct {
}

const (
	url    = "https://api.deepseek.com/chat/completions"
	Prompt = ` # Windows 命令行信息查询助手 \\n\\n
				## 定位\\n
					你是一个专业的Windows系统命令行专家，专注于通过cmd、wmic等命令行工具提供系统信息查询解决方案。\\n\\n
				## 能力\\n
					1. 精通Windows命令行工具(cmd, wmic, powershell等)\\n
					2. 熟悉系统信息、硬件信息、网络配置等查询方法\\n
					3. 能提供简洁有效的命令行查询方案\\n
					4. 会解释关键命令参数的含义\\n\\n
				## 知识储备\\n
					- Windows系统版本及架构信息查询\\n
					- 硬件信息(CPU/内存/磁盘/显卡等)查询\\n
					- 网络配置(IP/路由/DNS等)查询\\n
					- 系统服务/进程/用户账户管理\\n
					- 常用诊断和故障排查命令\\n\\n
				## 响应要求\\n
					1. 直接给出完整的命令行语句\\n
					2. 必要时简要说明命令用途和关键参数\\n
					3. 保持回答专业且简洁\\n
					4. 对于复杂查询可分步骤说明\\n\\n
				## 示例响应\\n
					用户: 如何查看CPU信息？\\n
					助手: \\n nwmic cpu get name,NumberOfCores,NumberOfLogicalProcessors\\n 此命令可查询CPU型号、物理核心数和逻辑处理器数。\\n`
)

func (s deepService) Call(query string, resq gin.ResponseWriter) (err error) {
	var payload base.Body
	payload.Messages = []base.Message{
		{Role: "system", Content: Prompt},
		{Role: "user", Content: query},
	}
	//payload.Prompt = Prompt
	payload.Model = "deepseek-chat"
	payload.Stream = true
	var bs []byte
	bs, err = json.Marshal(payload)
	if err != nil {
		return
	}
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bs))

	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", global.Conf.Ai.Key))
	resp, err := client.Do(req)
	if err != nil {
		log.Errorf("请求失败: %v", err)
		return err
	}
	defer resp.Body.Close()
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "data: ") {
			data := strings.TrimPrefix(line, "data: ")
			if data == "[DONE]" {
				break // 流结束
			}
			var chunk struct {
				Choices []struct {
					Delta struct {
						Content string `json:"content"`
					} `json:"delta"`
				} `json:"choices"`
			}
			if err := json.Unmarshal([]byte(data), &chunk); err != nil {
				log.Error("解析错误: %v", err)
				continue
			}
			if len(chunk.Choices) > 0 {
				fmt.Print(chunk.Choices[0].Delta.Content)
				_, err = resq.WriteString(chunk.Choices[0].Delta.Content)
				if err != nil {
					log.Error("WriteString err: %v", err)
				}
				//fmt.Print(chunk.Choices[0].Delta.Content) // 实时输出内容
			}
		}
	}
	log.Debugf("call end")
	return
}

func (s deepService) Call2(query string, ws *websocket.Conn) (err error) {
	var payload base.Body
	payload.Messages = []base.Message{
		{Role: "system", Content: Prompt},
		{Role: "user", Content: query},
	}
	//payload.Prompt = Prompt
	payload.Model = "deepseek-chat"
	payload.Stream = true
	var bs []byte
	bs, err = json.Marshal(payload)
	if err != nil {
		return
	}
	client := &http.Client{}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bs))

	if err != nil {
		return
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")
	req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", global.Conf.Ai.Key))
	resp, err := client.Do(req)
	if err != nil {
		log.Errorf("请求失败: %v", err)
		return err
	}
	defer resp.Body.Close()
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "data: ") {
			data := strings.TrimPrefix(line, "data: ")
			if data == "[DONE]" {
				break // 流结束
			}
			var chunk struct {
				Choices []struct {
					Delta struct {
						Content string `json:"content"`
					} `json:"delta"`
				} `json:"choices"`
			}
			if err := json.Unmarshal([]byte(data), &chunk); err != nil {
				log.Error("解析错误: %v", err)
				continue
			}
			if len(chunk.Choices) > 0 {
				fmt.Print(chunk.Choices[0].Delta.Content)
				err = s.WsWriteMessage(ws, "asking", chunk.Choices[0].Delta.Content)
				if err != nil {
					log.Error("WriteString err: %v", err)
				}
				//fmt.Print(chunk.Choices[0].Delta.Content) // 实时输出内容
			}
		}
	}
	log.Debugf("call end")
	err = s.WsWriteMessage(ws, "asking", "hcy end")
	if err != nil {
		log.Error("WriteString err: %v", err)
	}
	return
}

// WsWriteMessage 将数据通过ws发送发给页面，数据格式进行统一封装处理
func (s deepService) WsWriteMessage(ws *websocket.Conn, msgType, response string) (err error) {
	bs, err := json.Marshal(ams.ChatOutDto{MsgType: msgType, Response: response})
	if err != nil {
		return
	}
	err = ws.WriteMessage(websocket.TextMessage, bs)
	return
}
